package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.*;
import com.tanhua.common.pojo.*;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SoulService {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private SoulQuestionOptionMapper soulQuestionOptionMapper;

    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;

    @Autowired
    private QuestionnaireReportMapper questionnaireReportMapper;

    public List<QuestionListVo> SQuestionnaireLike() {
        //拿到用户id
        User user = UserThreadLocal.get();
        //要返回的vo对象
        List<QuestionListVo> QuestionListVoList = new ArrayList<>();
        //通过user_Id找到QuestionUserLock表中的user_id拿到问卷id和锁状态存到问卷vo里面
        QueryWrapper<QuestionUserLock> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", user.getId());
        List<QuestionUserLock> questionUserLock = this.questionUserLockMapper.selectList(queryWrapper1);
        for (QuestionUserLock questionUserLocks : questionUserLock) {
            QuestionListVo QuestionListVo = new QuestionListVo();
            QuestionListVo.setId(questionUserLocks.getQuestionnaireId());
            QuestionListVo.setIsLock(questionUserLocks.getIsLock());
            QuestionListVoList.add(QuestionListVo);
        }

        //拿出问卷Id的集合
        List<Long> questionnaireId = new ArrayList();
        for (QuestionUserLock UserId : questionUserLock) {
            questionnaireId.add(UserId.getQuestionnaireId());
            System.out.println(UserId.getQuestionnaireId());
        }

        //通过拿到的问卷id找到问题表中的数据存在返回问卷vo中
        QueryWrapper<Questionnaire> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id", questionnaireId);
        List<Questionnaire> soulQuestionnaire = this.questionnaireMapper.selectList(queryWrapper2);
        for (Questionnaire questionnaire : soulQuestionnaire) {
            for (QuestionListVo QuestionListVo : QuestionListVoList) {
                //把返回vo中的id与从问题表中拿到的id进行对比,确定存放的是同一个vo返回对象
                if (questionnaire.getId().toString().equals(QuestionListVo.getId().toString())) {
                    QuestionListVo.setLevel(questionnaire.getLevel());
                    QuestionListVo.setName(questionnaire.getName());
                    QuestionListVo.setCover(questionnaire.getCover());
                    QuestionListVo.setStar(questionnaire.getStar());
                }
            }
        }

        //把问题vo填充到问卷vo中
        for (QuestionListVo QuestionListVo : QuestionListVoList) {
            //拿到试题数据
            QueryWrapper<SoulQuestion> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("questionnaire_id", questionnaireId);
            //从数据库中拿到QuestionVo信息
            List<SoulQuestion> soulQuestions = this.soulQuestionMapper.selectList(queryWrapper3);
            List<QuestionVo> QuestionVos = new ArrayList<>();
            //填充QuestionVo的数据
            for (SoulQuestion soulQuestion : soulQuestions) {
                QuestionVo QuestionVo = new QuestionVo();
                QuestionVo.setId(String.valueOf(soulQuestion.getId()));
                QuestionVo.setQuestion(soulQuestion.getStem());
                QuestionVos.add(QuestionVo);
                //QuestionVo中还有一个List<OptionVo> options-----选项集合没有填充
                QueryWrapper<SoulQuestionOption> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.in("question_id", soulQuestion.getId());
                List<SoulQuestionOption> soulQuestionList = this.soulQuestionOptionMapper.selectList(queryWrapper4);
                List<OptionVo> OptionVo = new ArrayList<>();
                //填充OptionVo1数据
                for (SoulQuestionOption option : soulQuestionList) {
                    OptionVo OptionVo1 = new OptionVo();
                    OptionVo1.setId(String.valueOf(option.getId()));
                    OptionVo1.setOption(option.getContent());
                    OptionVo.add(OptionVo1);
                }
                //把选项vo集合填充到问题对象中
                QuestionVo.setOptions(OptionVo);
            }
            //把问题对象填充到返回问卷vo对象
            QuestionListVo.setQuestions(QuestionVos);

        }
        for (QuestionListVo questionListVo : QuestionListVoList) {
            System.out.println(questionListVo);
        }
        return QuestionListVoList;
    }

    /**
     * 测灵魂题目提交
     *
     * @param answersList
     */
    public void testSoul(List<Answers> answersList) {
        Integer score = 0;
        Long questionId = 0L;

        //计算分数
        for (Answers answers : answersList) {
            questionId = answers.getQuestionId();
            Long optionId = answers.getOptionId();
            QueryWrapper queryWrapper = new QueryWrapper();
            //queryWrapper.eq("question_id", questionId);
            queryWrapper.eq("id", optionId);
            SoulQuestionOption soulQuestionOption = soulQuestionOptionMapper.selectOne(queryWrapper);
            score += Integer.parseInt(soulQuestionOption.getScore());
        }

        System.out.println(score);

        //通过题目id查到对应的问卷id
        SoulQuestion soulQuestion = soulQuestionMapper.selectById(questionId);
        Long questionnaireId = soulQuestion.getQuestionnaireId();

        //默认初级开启
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper();
        if (questionnaireId<=2){
            queryWrapper.eq("questionnaire_id", questionnaireId+1);
            QuestionUserLock questionUserLock = questionUserLockMapper.selectOne(queryWrapper);
            if(questionUserLock.getIsLock().equals(1)){
                questionUserLock.setIsLock(0);
                questionUserLockMapper.update(questionUserLock,queryWrapper);
            }
        }
        //根据问卷id,查看结果表，看总分在哪个区间，判断你的性格，并把数据都添加到报告表里
        QueryWrapper<QuestionnaireResult> query3 = new QueryWrapper<>();
        query3.eq("questionnaire_id", questionnaireId);
        List<QuestionnaireResult> questionnaireResults = questionnaireResultMapper.selectList(query3);

        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        questionnaireReport.setUserId(UserThreadLocal.get().getId());
        questionnaireReport.setQuestionnaireId(questionnaireId);
        for (QuestionnaireResult questionnaireResult : questionnaireResults) {
            String[] split = questionnaireResult.getScope().split(",");
            if (score >= Integer.valueOf(split[0]) && score <= Integer.valueOf(split[1])) {
                questionnaireReport.setResultId(questionnaireResult.getId());
                break;
            }
        }
        questionnaireReportMapper.insert(questionnaireReport);
    }

    /**
     * 灵魂测试结果
     * @param id
     * @return
     */
    public TestResultVo testResult(Long id) {
        TestResultVo testResultVo = new TestResultVo();
        List<Dimensions> dimensionList = new ArrayList<>();
        //通过id获取报告里面的数据
        QuestionnaireReport questionnaireReport = questionnaireReportMapper.selectById(id);
        Long resultId = questionnaireReport.getResultId();
        //通过报告表里面的resultId查询数据，写维度集合里
        QuestionnaireResult questionnaireResult = questionnaireResultMapper.selectById(resultId);
        dimensionList.add(new Dimensions("extroversion",questionnaireResult.getExtroversion()));
        dimensionList.add(new Dimensions("judgement",questionnaireResult.getJudgement()));
        dimensionList.add(new Dimensions("abstraction",questionnaireResult.getAbstraction()));
        dimensionList.add(new Dimensions("rationality",questionnaireResult.getRationality()));

        //保存到testResultVo里面
        testResultVo.setConclusion(questionnaireResult.getContent());
        testResultVo.setCover(questionnaireResult.getCover());
        testResultVo.setDimensions(dimensionList);

        //通过resultId查询报告表，获取所有的用户，存到集合里
        QueryWrapper<QuestionnaireReport> queryWrapper = new QueryWrapper();
        queryWrapper.eq("result_id",resultId);
        List<QuestionnaireReport> questionnaireReports = questionnaireReportMapper.selectList(queryWrapper);
        List<Long> userIds = new ArrayList<>();
        for (QuestionnaireReport report : questionnaireReports) {
            userIds.add(report.getUserId());
        }


        //查询所有用户的完整信息
        QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper();
        queryWrapper1.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper1);

        ArrayList<SimilarYou> similarYouList = new ArrayList<>();
        //如果是当前用户就跳过，否则添加到相似的人集合里
        for (UserInfo userInfo : userInfoList) {
            if(UserThreadLocal.get().getId().equals(userInfo.getUserId())){
                continue;
            }
            similarYouList.add(new SimilarYou(userInfo.getUserId(),userInfo.getLogo()));
        }

        testResultVo.setSimilarYou(similarYouList);
        return testResultVo;
    }
}
